<template>
  <div>
    <TopFilter :list="topFilterList" :cols="3" :labelWidth="130" @filterChange="changeHandle" @onCollapse="collapseHandle" :collapse="collapse"></TopFilter>
    <FilterTable
      ref="table"
      selectionType="single"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      columnsRef="customerRepair_customerinfo_ownerVehicleManagement_main"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="onRowSelectChange"
    >
      <!-- :onSyncTableData="handleTbaleChange" -->
      <template slot="controls">
        <el-button size="small" type="primary" @click="() => this.openHandler('carInfo', {})">车辆档案</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="() => this.openHandler('addCar', {})" :disabled="disabledS">新建车辆档案</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="() => this.openHandler('addOwner', {})">新建车主档案</el-button>
        <AjaxButton size="small" type="primary" icon="el-icon-download" :click="ownerExportData">车主信息导出</AjaxButton>
        <AjaxButton size="small" type="primary" icon="el-icon-plus" :click="saveDealerOwner">生成经销商车主</AjaxButton>
      </template>
    </FilterTable>
    <Drawer :visible.sync="actionsOwner.visible" :title="actionsOwner.title" width="60%" destroyOnClose :containerStyle="{ height: '100%', overflow: 'auto' }">
      <addOwnerPanel :type.sync="actionsOwner.type" :resData="this.resData" @close="closeHandler" />
    </Drawer>
    <Drawer :visible.sync="actions.visible" :title="actions.title" width="70%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Vehicle :type.sync="actions.type" :isSelectColumn="false" :parentData="this.resData" @close="closeVehicle" />
    </Drawer>
    <Drawer :visible.sync="actionsVehicle.visible" :title="actionsVehicle.title" width="70%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addVehiclePanel :type.sync="actionsVehicle.type" :resData="this.resData" @close="closeAddVehicle" />
    </Drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import addOwnerPanel from './addOwnerPanel';
import Vehicle from './vehicle';
import addVehiclePanel from './addVehiclePanel';
import { exportExcelFile } from '@/utils/index';
import { confirmAction, notifyAction, isFormEmpty } from '@/utils';
import { getAllUser } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import { getOwnerInfo, getOwnerExcelList, getProvince, getCitys, getDistrict, getRegion, saveDealerOwner } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import ComplaintHistory from '@/pages/repair/business/customer/combination/complaint';
import { menuUserAction } from '@/api/repair/repairReception/repairBusinessManger';

export default {
  name: 'ownerVehicleManage',
  components: {
    addOwnerPanel,
    addVehiclePanel,
    Vehicle
  },
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    this.type = '';
    this.resData = {};
    this.title = '';
    this.selectedRow = null;
    return {
      isHidden: 'none',
      collapse: false,
      editAuth: true,
      topFilterList: this.createTopFilterList(),
      visible: false,
      actions: { visible: false, type: '', title: '' },
      actionsOwner: { visible: false, type: '', title: '' },
      actionsVehicle: { visible: false, type: '', title: '' },
      showComplaintHistory: false, // 显示投诉历史dialog
      ownerSelect: true,
      fetchApi: getOwnerInfo,
      fetchParams: { pageNum: 1, xhrAbort: true },
      columns: this.createTableColumns(),
      isExportExcel1: false,
      disabledS: true,
      regionList: []
    };
  },
  created() {
    this.getAllUser();
    this.getProvine();
  },
  mounted() {
    this.BaseTable = this.$refs.table;
    this.menuUserAction();
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'ownerNo'
        },
        {
          type: 'INPUT',
          label: '客户姓名',
          fieldName: 'ownerName'
        },
        {
          type: 'INPUT',
          label: '客户手机',
          fieldName: 'mobile'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          // disabled={this.editAuth}  编辑按钮级权限 此代码在 <el-button size="mini" type="text" 后写入
          render: props => {
            return (
              <div style="text-align:center">
                <el-button size="mini" type="text" onClick={() => this.openHandler('editOwner', props.row)}>
                  编辑
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" onClick={() => this.openHandler('detailOwner', props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '客户性质',
          dataIndex: 'ownerProperty',
          width: 120,
          showOverflowTooltip: true,
          dictItems: this.createDictList(8011),
          render: props => {
            return <span>{this.createDictText(props.row.ownerProperty, 8011)}</span>;
          }
        },
        {
          title: '客户编号',
          dataIndex: 'ownerNo',
          width: 120,
          showOverflowTooltip: true
        },
        {
          title: '客户姓名',
          dataIndex: 'ownerName',
          width: 90,
          showOverflowTooltip: true
        },
        {
          title: '性别',
          dataIndex: 'gender',
          width: 90,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.gender, 8012)}</span>;
          }
        },
        {
          title: '客户电话',
          dataIndex: 'phone',
          showOverflowTooltip: true
        },
        {
          title: '客户手机号',
          dataIndex: 'mobile',
          showOverflowTooltip: true
        },
        {
          title: '证件类型',
          dataIndex: 'ctCode',
          width: 150,
          showOverflowTooltip: true,
          render: props => {
            return <div>{this.createDictText(props.row.ctCode, 8013)}</div>;
          }
        },
        {
          title: '证件号码',
          dataIndex: 'certificateNo',
          width: 130,
          showOverflowTooltip: true
        },
        {
          title: '传真',
          dataIndex: 'fax',
          width: 130,
          showOverflowTooltip: true
        },
        {
          title: 'E-mail',
          dataIndex: 'email',
          showOverflowTooltip: true
        },
        {
          title: '省份',
          dataIndex: 'province',
          width: 150,
          dictItems: [],
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.getText(props.row.province)}</span>;
          }
        },
        {
          title: '城市',
          dataIndex: 'city',
          width: 150,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.getText(props.row.city)}</span>;
          }
        },
        {
          title: '区/县',
          dataIndex: 'district',
          width: 150,
          sorter: true,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.getText(props.row.district)}</span>;
          }
        },
        {
          title: '邮编',
          dataIndex: 'zipCode',
          width: 90,
          showOverflowTooltip: true
        },

        {
          title: '居住地址',
          dataIndex: 'address',
          width: 150,
          showOverflowTooltip: true
        },
        {
          title: '单位性质',
          dataIndex: 'industryFirst',
          showOverflowTooltip: true,
          itemList: this.createDictList(8251),
          render: props => {
            return <span>{this.createDictText(props.row.industryFirst, 8251)}</span>;
          }
        },
        {
          title: '行业类型',
          dataIndex: 'industrySecond',
          showOverflowTooltip: true,
          dictItems: this.createDictList(8252),
          render: props => {
            return <span>{this.createDictText(props.row.industrySecond, 8252)}</span>;
          }
        },
        {
          title: '职业',
          dataIndex: 'vocationType',
          dictItems: this.createDictList(8022),
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.vocationType, 8022)}</span>;
          }
        },
        {
          title: '职称',
          dataIndex: 'position',
          dictItems: this.createDictList('8023'),
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.position, '8023')}</span>;
          }
        },
        {
          title: '生日',
          dataIndex: 'birthday',
          width: 100,
          showOverflowTooltip: true
        },
        {
          title: '婚姻状况',
          dataIndex: 'ownerMarriage',
          width: 100,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.ownerMarriage, 8018)}</span>;
          }
        },
        {
          title: '喜欢联系方式',
          dataIndex: 'bestConcatType',
          width: 100,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.bestConcatType, 9123)}</span>;
          }
        },
        {
          title: '爱好',
          dataIndex: 'hobbyName',
          width: 100,
          showOverflowTooltip: true,
          render: props => {
            return <span>{props.row.hobby && this.translateHobby(props.row.hobby)}</span>;
          }
        },
        {
          title: '子女状况',
          dataIndex: 'isChlidren',
          width: 100,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.isChlidren, 1004)}</span>;
          }
        },
        {
          title: '家庭年收入',
          dataIndex: 'familyIncome',
          width: 100,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.familyIncome, 1290)}</span>;
          }
        }
      ];
    },
    translateHobby(hobbyStr) {
      let arr = hobbyStr.split(',').map(item => this.createDictText(item, 8020));
      return arr.join(',');
    },
    async getProvine() {
      const res = await getProvince();
      const provinceList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
      // this.topFilterList.find(item => item.fieldName === 'province').itemList = provinceList;
      const allRegion = await getRegion();
      this.regionList = allRegion.data.map(x => ({ value: x.regionId, text: x.regionName }));
      this.columns.find(x => x.dataIndex === 'province').filterItems = provinceList;
    },
    async menuUserAction() {
      let res = await menuUserAction();
      for (const item of res.data) {
        if (item.actionUrl === '777777') {
          this.isHidden = '';
        }
        if (item.actionUrl === '111111') {
          this.editAuth = false;
        }
      }
    },
    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    async provinceChange(regionId) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'city'));
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'district'));
      if (!regionId) return;
      const res = await getCitys(regionId);
      // this.topFilterList.find(item => item.fieldName === 'city').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
    },
    async cityChange(regionId) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'district'));
      if (!regionId) return;
      const res = await getDistrict(regionId);
      // this.topFilterList.find(item => item.fieldName === 'district').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
    },
    // 所有用户
    async getAllUser() {
      // const res = await getAllUser();
      // console.log('所有用户', res);
      // this.columns.find(item => item.dataIndex === 'CREATED_BY').editItems = res.data.map(x => ({ value: x.userId + '', text: x.employeeName }));
    },
    openHandler(type, val) {
      if (type === 'addOwner') {
        this.actionsOwner = { visible: true, type: 'add', title: '新增车主信息' };
      } else if (type === 'editOwner') {
        this.actionsOwner = { visible: true, type: 'edit', title: '编辑车主信息' };
        this.resData = val;
      } else if (type === 'detailOwner') {
        this.actionsOwner = { visible: true, type: 'show', title: '车主信息明细' };
        this.resData = val;
      } else if (type === 'addCar') {
        if (isFormEmpty(this.selectedRow)) {
          try {
            return notifyAction('请选择一条数据！', 'warning');
          } catch (err) {}
        }
        this.actionsVehicle = { visible: true, type: 'add', title: '新增车辆信息' };
        this.resData = this.selectedRow;
      } else if (type === 'carInfo') {
        this.resData = {};
        if (!isFormEmpty(this.selectedRow)) {
          this.resData = this.selectedRow;
        }
        this.actions = { visible: true, type: 'add', title: '车辆信息' };
      }
    },
    onRowSelectChange(row) {
      this.disabledS = true;
      if (!row.length) {
        this.selectedRow = null;
      } else {
        this.disabledS = false;
        this.selectedRow = row[0];
      }
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });
    },
    collapseHandle() {
      this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    },
    closeVehicle(val) {
      this.actions.visible = val;
    },
    closeAddVehicle(refesh) {
      this.actionsVehicle.visible = false;
      refesh && (this.fetchParams = { ...this.fetchParams });
    },
    closeHandler(refesh) {
      this.actionsOwner.visible = false;
      console.log(refesh);
      refesh && (this.fetchParams = { ...this.fetchParams });
    },

    getText(val) {
      return this.regionList.find(x => x.value === val) ? this.regionList.find(x => x.value === val).text : '';
    },
    // 车主导出
    async ownerExportData() {
      await getOwnerExcelList(this.fetchParams).then(res => {
        console.log(res);
        exportExcelFile(res.data, '车主信息');
      });
    },
    async saveDealerOwner() {
      let res = await saveDealerOwner();
      if (res.resultCode == 200) {
        notifyAction('操作成功', 'success');
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
